package com.agileai.miscdp.hotweb.ui.actions.pickfill;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IProgressService;

import com.agileai.miscdp.hotweb.domain.pickfill.PickFillFuncModel;
import com.agileai.miscdp.hotweb.generator.pickfill.PFMHandlerCfgGenerator;
import com.agileai.miscdp.hotweb.generator.pickfill.PFMHandlerGenerator;
import com.agileai.miscdp.hotweb.generator.pickfill.PFMJspPagGenerator;
import com.agileai.miscdp.hotweb.generator.pickfill.PFMServiceCfgGenerator;
import com.agileai.miscdp.hotweb.generator.pickfill.PFMServiceClassGenerator;
import com.agileai.miscdp.hotweb.generator.pickfill.PFMServiceInterfaceGenerator;
import com.agileai.miscdp.hotweb.generator.pickfill.PFMSqlMapCfgGenerator;
import com.agileai.miscdp.hotweb.generator.pickfill.PFMSqlMapGenerator;
import com.agileai.miscdp.hotweb.ui.actions.BaseGenCodesAction;
import com.agileai.miscdp.hotweb.ui.dialogs.CodeGenConfigDialog;
import com.agileai.miscdp.hotweb.ui.editors.pickfill.PickFillModelEditor;
import com.agileai.miscdp.hotweb.ui.editors.pickfill.PickFillModelEditorContributor;
import com.agileai.miscdp.util.DialogUtil;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.domain.KeyNamePair;
import com.agileai.util.FileUtil;
import com.agileai.util.StringUtil;

/**
 * 代码生成动作
 */
public class PFMGenCodesAction extends BaseGenCodesAction{
	private static final String GenOptionSection = "PickFillModelEditor.GeneratorOption";
	
	public PFMGenCodesAction() {
		super();
	}
	public void setContributor(PickFillModelEditorContributor contributor) {
		this.contributor = contributor;
	}
	public void run() {
		PickFillModelEditor modelEditor = (PickFillModelEditor)this.getModelEditor();
    	String listJspName = modelEditor.getQMBasicConfigPage().getQMExtendAttribute().getListJspNameText().getText();
    	if (StringUtil.isNullOrEmpty(listJspName)){
    		String listJspCheckNullMsg = MiscdpUtil.getIniReader().getValue("PickFillModelEditor","ListJspCheckNullMsg");
    		DialogUtil.showInfoMessage(listJspCheckNullMsg);
    		return;
    	}
    	String codeFieldValue = modelEditor.getQMBasicConfigPage().getCodeFieldText().getText();
    	if (StringUtil.isNullOrEmpty(codeFieldValue)){
    		String codeFieldCheckNullMsg = MiscdpUtil.getIniReader().getValue("PickFillModelEditor","CodeFieldCheckNullMsg");
    		DialogUtil.showInfoMessage(codeFieldCheckNullMsg);
    		return;
    	}
    	String nameFieldValue = modelEditor.getQMBasicConfigPage().getNameFieldText().getText();
    	if (StringUtil.isNullOrEmpty(nameFieldValue)){
    		String nameFieldCheckNullMsg = MiscdpUtil.getIniReader().getValue("PickFillModelEditor","NameFieldCheckNullMsg");
    		DialogUtil.showInfoMessage(nameFieldCheckNullMsg);
    		return;
    	}
		Shell shell = modelEditor.getSite().getShell();
    	if (modelEditor.isDirty()){
    		String confirmTitle = MiscdpUtil.getIniReader().getValue("DialogInfomation","ConfirmTitle");
    		String confirmMsg = MiscdpUtil.getIniReader().getValue("DialogInfomation","IsSaveFirst");
    		boolean saveFirst = MessageDialog.openConfirm(shell, confirmTitle, confirmMsg);
    		if (saveFirst){
    			modelEditor.doSave(new NullProgressMonitor());
    		}else{
    			return;
    		}
    	}
    	funcModel = modelEditor.buildFuncModel();
		CodeGenConfigDialog configDialog = new CodeGenConfigDialog(shell);
		List<KeyNamePair> inputGenList = new ArrayList<KeyNamePair>();
		inputGenList = MiscdpUtil.getIniReader().getList(GenOptionSection);
		configDialog.setInputGenList(inputGenList);
		configDialog.open();
		if (configDialog.getReturnCode() != Dialog.OK){
			return;
		}
		genertorMap = configDialog.getSelectedKeyNamePairs();
    	
    	IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
		try {
	    	String projectName = funcModel.getProjectName();
	    	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
			progressService.runInUI(progressService,this,project);
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public void run(IProgressMonitor monitor) throws InvocationTargetException,
			InterruptedException {
		monitor.beginTask("init model values:", 1000);
		monitor.subTask("set model values....");
		monitor.worked(50);
		
    	String projectName = funcModel.getProjectName();
    	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
    	File xmlFile = getXmlFile();
    	
    	String sqlMapFile = ((PickFillFuncModel)funcModel).getSqlMapFile();
		File sqlMap = new File(sqlMapFile);
		File parentFile = sqlMap.getParentFile();
		if (!parentFile.exists()){
			parentFile.mkdirs();
		}
		String fileName = sqlMap.getName();
		String sqlNameSpace = fileName.substring(0,fileName.length()-4);
		((PickFillFuncModel)funcModel).setSqlNameSpace(sqlNameSpace);
    	
    	if (genertorMap.containsKey(GEN_OPTION_JSPPAGE)){
        	monitor.subTask("generating jsp files....");
    		monitor.worked(200);
    		PFMJspPagGenerator sMJspPagGenerator = new PFMJspPagGenerator();
    		sMJspPagGenerator.setXmlFile(xmlFile);
        	String listJspName = project.getLocation().toString()+"/WebRoot/jsp/"+((PickFillFuncModel)funcModel).getListJspName();
    		sMJspPagGenerator.setListJspFile(listJspName);
    		sMJspPagGenerator.generate();
    	}
    	
		if (genertorMap.containsKey(GEN_OPTION_SQLMAP_INDEX)){
			monitor.subTask("generating SqlMap Index files....");
			monitor.worked(250);
			PFMSqlMapCfgGenerator sMSqlMapGenerator = new PFMSqlMapCfgGenerator();
			String abstSqlMapCfgPath = project.getLocation().toString()+"/src/SqlMapConfig.xml";
			sMSqlMapGenerator.setConfigFile(abstSqlMapCfgPath);
			sMSqlMapGenerator.setSqlMapFileName(sqlNameSpace);
			sMSqlMapGenerator.generate();
		}

    	if (genertorMap.containsKey(GEN_OPTION_SQLMAP_DEFINE)){
    		monitor.subTask("generating SqlMap files....");
    		monitor.worked(300);
    		PFMSqlMapGenerator sMSqlMapGenerator = new PFMSqlMapGenerator();
    		String findRecordsSql = funcModel.getListSql();
    		sMSqlMapGenerator.setFindRecordsSql(findRecordsSql);
        	sMSqlMapGenerator.setSqlMapFile(sqlMapFile);
        	sMSqlMapGenerator.setFuncModel((PickFillFuncModel)funcModel);
    		sMSqlMapGenerator.generate();
    	}
		
    	if (genertorMap.containsKey(GEN_OPTION_SERVICE_CONFIG)){
    		monitor.subTask("generating Service config files....");
    		monitor.worked(500);
    		PFMServiceCfgGenerator sMServiceCfgGenerator = new PFMServiceCfgGenerator();
    		String abstServiceCfgPath = project.getLocation().toString()+"/src/ServiceContext.xml";
    		sMServiceCfgGenerator.setConfigFile(abstServiceCfgPath);
    		sMServiceCfgGenerator.setFuncModel((PickFillFuncModel)funcModel);
    		sMServiceCfgGenerator.generate();
    	}

    	if (genertorMap.containsKey(GEN_OPTION_HANDLER_CONFIG)){
    		monitor.subTask("generating Handler config files....");
    		monitor.worked(600);
    		PFMHandlerCfgGenerator sMHandlerCfgGenerator = new PFMHandlerCfgGenerator();
    		String abstHandlerCfgPath = project.getLocation().toString()+"/src/HandlerContext.xml";
    		sMHandlerCfgGenerator.setConfigFile(abstHandlerCfgPath);
    		sMHandlerCfgGenerator.setFuncModel((PickFillFuncModel)funcModel);
    		sMHandlerCfgGenerator.generate();
    	}

		
		String srcDir = project.getLocation().toString()+"/src";
		
		if (genertorMap.containsKey(GEN_OPTION_HANDLER_CLASS)){
			monitor.subTask("generating Handler java files....");
			monitor.worked(700);
			
			PFMHandlerGenerator sMHandlerGenerator = new PFMHandlerGenerator();
			sMHandlerGenerator.setSrcPath(srcDir);
			PickFillFuncModel standardFuncModel = (PickFillFuncModel)funcModel;
			String listHandlerClassName = standardFuncModel.getListHandlerClass();
			sMHandlerGenerator.setListHandlerClassName(listHandlerClassName);
			sMHandlerGenerator.setXmlFile(xmlFile);
			sMHandlerGenerator.generate();
		}
		
		if (genertorMap.containsKey(GEN_OPTION_SERVICE_INTERFACE)){
			monitor.subTask("generating Service Impl java files....");
			monitor.worked(800);
			PFMServiceClassGenerator sMServiceClassGenerator = new PFMServiceClassGenerator();
			String implFullClassName = funcModel.getImplClassName();
			File implJavaFile = FileUtil.createJavaFile(srcDir, implFullClassName);
			String implJavaFilePath = implJavaFile.getAbsolutePath();
			sMServiceClassGenerator.setJavaFile(implJavaFilePath);
			sMServiceClassGenerator.setXmlFile(xmlFile);
			sMServiceClassGenerator.generate();
			
    		try {
				MiscdpUtil.getJavaFormater().format(implJavaFilePath, sMServiceClassGenerator.getCharencoding());
			} catch (IOException e1) {
				e1.printStackTrace();
				throw new InvocationTargetException(e1);
			}
		}

		if (genertorMap.containsKey(GEN_OPTION_SERVICE_IMPL)){
			monitor.subTask("generating Service Interface java files....");
			monitor.worked(900);
			PFMServiceInterfaceGenerator sMServiceInterfaceGenerator = new PFMServiceInterfaceGenerator();
			String interfaceClassName = funcModel.getInterfaceName();
			File interfaceJavaFile = FileUtil.createJavaFile(srcDir, interfaceClassName);
			String interfaceJavaFilePath = interfaceJavaFile.getAbsolutePath();
			sMServiceInterfaceGenerator.setJavaFile(interfaceJavaFilePath);
			sMServiceInterfaceGenerator.setXmlFile(xmlFile);
			sMServiceInterfaceGenerator.generate();
			
    		try {
				MiscdpUtil.getJavaFormater().format(interfaceJavaFilePath, sMServiceInterfaceGenerator.getCharencoding());
			} catch (IOException e1) {
				e1.printStackTrace();
				throw new InvocationTargetException(e1);
			}
		}
		
		try {
			project.refreshLocal(IResource.DEPTH_INFINITE, null);
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}
}
